import { createStore } from 'vuex'
import {
	getWeixinToken,
	getUserPhone,
	MemgerWhetherRegister,
	MemgerRegisterWrite,
	MemgerRegisterWriteForm,
	getWeixinOpenid,
	ReadBackgroundImageInfor,
	ReadBannerImageInfor,
	ReadFontInfor,
	ReadChangeLensesRule,
	ReadNearbyShopInfor,
	ReadIntroduceMainTitle,
	ReadIntroduceDeputyTitle,
	ReadIntroduceSubTitle,
	ReadIntroduceContent,
	EstablishWearerInfor,
	ReadWearerInfor,
	EditVisionArchivesInfor,
	EditMyCollect,
	ReadMyCollect,
	SecurityCodeCheck,
	ReadVisionArchivesInfor,
	ReMoveVisionArchivesInfor,
	StarDreambActivate,
	ReadStarDreambInfor,
	ReadChildInforProtectRule,
	ReadTermAgreement,
	StarDreambVisionReview,
	ReadStarDreambCurInfor,
	ReadStarDreambVisionReviewInfor,
	ReadMemberReceive,
	ApplyChangeLensSubmit,
} from "./api"
import {
	randomString
} from "../pages/common/utils"

import IcMan from "../static/ic_man.png";
import IcWomen from "../static/ic_women.png";
import IcBoy from "../static/ic_boy.png";
import IcGirl from "../static/ic_girl.png";
import IcFather from "../static/ic_father.png";
import IcMother from "../static/ic_mother.png";

function rad(d) {
	return d * Math.PI / 180.0;
}
function getDistance(lat1, lng1, lat2, lng2) {
	const radLat1 = rad(lat1);
	const radLat2 = rad(lat2);
	const a = radLat1 - radLat2;
	const b = rad(lng1) - rad(lng2)
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toFixed(2)
	return s;
}

const store = createStore({
	state:{//存放状态
		access_token: '', // 微信TOKEN
		expires_in: 0, // 微信TOKEN有效期
		isLogin: false,
		userInfo: {},
	    openid: '',
		tabIndex: 0,
		statusBarHeight: 0,
		navBarHeight: 0,
		screenWidth: 0,
		images: {
			home_1: '',
			home_2: '',
			search_1: '',
			search_2: '',
			my_1: '',
			xmb_1: '',
			xmb_2: '',
			doc_1: '',
			banner: '',
		},
		banners: [],
		fonts: {
			ltmyj: 'https://gitee.com/zhangsina520/ltmyj/raw/main/unpackage/font.ttf'
			// ltmyj: '',
		},
		activityContent: '',
		nearbyShop: [],
		latitude: 0,
		longitude: 0,
		province: '',
		city: '',
		district: '',
		formatted_address: '',
		readIntroduceMainTitle: [], // 了解星梦圆目录
		readIntroduceSubDir: [], // 了解星梦圆内容,子目录和文章标题
		readIntroduceContent: '', // 打开内容
		wearers: [], // 佩戴者
		visionArchives: [], // TA的视力档案
		selectedWearerIndex: -1,
		allStores: [], // 所有门店，选择的时候使用
		myDocCollect: [], // 文章收藏
		myShopCollect: [], //店铺收藏
		checkResult: null, // 查验防伪结果
		docEditItem: null, // 编辑的档案
		starHistory: null, // 星梦保历史记录
		ruleContent: '', // 星梦圆儿童个人信息保护规则
		termAgreement: '', // 条款协议
		StarDreambCurInfor: [], // 星梦保当前信息
		StarDreambVisionReviewInfor: [], // 星梦保视力复查记录
	},
	mutations: {
		setLogin(state, { isLogin, userInfo }) {
			if (!isLogin) {
				userInfo = {};
			}
			state.isLogin = isLogin;
			state.userInfo = userInfo;
		},
		changeTabIndex(state, tabIndex) {
			state.tabIndex = tabIndex;
		},
		changeNavBarHeight(state, navBarHeight) {
			state.navBarHeight = navBarHeight;
		},
		changeScreenWidth(state, screenWidth) {
			state.screenWidth = screenWidth
		},
		changeStatusBarHeight(state, statusBarHeight) {
			state.statusBarHeight = statusBarHeight
		},
		setFontFile(state, fontFile) {
			if (fontFile.startsWith("http://")) {
				fontFile = fontFile.replaceAll("http://", "https://");
			}
			// state.fonts.ltmyj = fontFile;
			state.fonts.ltmyj = 'https://gitee.com/zhangsina520/ltmyj/raw/main/unpackage/font.ttf';
		},
		setActivityContent(state, activityContent) {
			state.activityContent = activityContent;
		},
		setNearbyShop(state, nearbyShop) {
			state.nearbyShop = nearbyShop;
		},
		setAllStores(state, allStores) {
			state.allStores = allStores
		},
		setCollect(state, {myDocCollect, myShopCollect}) {
			state.myShopCollect = myShopCollect
			state.myDocCollect = myDocCollect
		},
		setLocation(state, {latitude, longitude, regeocodeData}) {
			state.longitude = longitude;
			state.latitude = latitude;
			if (regeocodeData) {
				const {
					province,
					city,
					district, // 区
				} = regeocodeData.addressComponent
				// 格式化地址，eg "广东省深圳市盐田区海山街道深圳市盐田区人民政府盐田区行政中心大楼"
				const formatted_address = regeocodeData.formatted_address

				state.province = province
				state.city = city
				state.district = district
				state.formatted_address = formatted_address
			}
		},
		setReadIntroduceMainTitle(state, readIntroduceMainTitle) {
			state.readIntroduceMainTitle = readIntroduceMainTitle;
		},
		setReadIntroduceSubDir(state, readIntroduceSubDir) {
			state.readIntroduceSubDir = readIntroduceSubDir;
		},
		setIntroduceContent(state, introduceContent){
			state.readIntroduceContent = introduceContent;
		},
		setBanners(state, banners) {
			state.banners = banners.map((banner) => {
				let {ImageFile} = banner;
				// if (ImageFile.startsWith("http://")) {
				// 	ImageFile = ImageFile.replaceAll("http://", "https://");
				// 	console.log('ImageFile', ImageFile)
				// }
				return {...banner, ImageFile};
			});
		},
		setWeixinOpenId(state, openid) {
			state.openid = openid;
		},
		setWeixinToken(state, { access_token, expires_in }) {
			state.access_token = access_token;
			state.expires_in = expires_in;
		},
		setImages(state, images) {
			images.forEach((item) => {
				let { ImageMark, ImageFile } = item;
				// if (ImageFile.startsWith("http://")) {
				// 	ImageFile = ImageFile.replaceAll("http://", "https://");
				// }
				switch(ImageMark) {
					case "首页头图":
						console.log(`${ImageMark} -> ${ImageFile}`);
						state.images.home_1 = ImageFile;
						break;
					case "首页底图":
						state.images.home_2 = ImageFile;
						break;
					case "首页banner图":
						state.images.banner = ImageFile;
						break;
					case "门店搜索图":
						state.images.search_1 = ImageFile;
						break;
					case "门店详情图":
						state.images.search_2 = ImageFile;
						break;
					case "我的头图":
						state.images.my_1 = ImageFile;
						break;
					case "换新片图":
						state.images.xmb_1 = ImageFile;
						break;
					case "激活步骤图":
						state.images.xmb_2 = ImageFile;
						break;
					case "视力档案图":
						state.images.doc_1 = ImageFile;
						break;
				}
			});
		},
		setWearers(state, wearers) {
			state.wearers = wearers.map((wearer) => {
				let Icon = IcMan;
				if (wearer.WearerSex === "女") {
					if (wearer.WearerAge < 18) {
						Icon = IcGirl;
					} else if (wearer.WearerAge >= 18 && wearer.WearerAge < 60) {
						Icon = IcWomen;
					} else {
						Icon = IcMother;
					}
				}
				if (wearer.WearerSex === "男") {
					if (wearer.WearerAge < 18) {
						Icon = IcBoy;
					} else if (wearer.WearerAge >= 18 && wearer.WearerAge < 60) {
						Icon = IcMan;
					} else {
						Icon = IcFather;
					}
				}
				return {...wearer, Icon};
			});
			if (state.selectedWearerIndex < 0 && wearers && wearers.length > 0) {
				state.selectedWearerIndex = 0
			}
		},
		setVisionArchives(state, VisionArchives) {
			// VhId 大的排前面
			state.visionArchives = VisionArchives.sort((a, b) => {
				if (a.VhId > b.VhId) {
					return -1
				} else if (a.VhId < b.VhId) {
					return 1
				}
				return 0;
			});
		},
		selectWearer(state, index) {
			console.log("selectWearer", index)
			state.selectedWearerIndex = index;
		},
		setCheckResult(state, checkResult) {
			state.checkResult = checkResult
		},
		setDocEditItem(state, docEditItem) {
			state.docEditItem = docEditItem
		},
		setStarHistory(state, starHistory) {
			state.starHistory = starHistory;
		},
		setRuleContent(state, ruleContent) {
			state.ruleContent = ruleContent;
		},
		setTermAgreement(state, termAgreement) {
			state.termAgreement = termAgreement;
		},
		setStarDreambCurInfor(state, StarDreambCurInfor) {
			state.StarDreambCurInfor = StarDreambCurInfor
		},
		setStarDreambVisionReviewInfor(state, StarDreambVisionReviewInfor) {
			state.StarDreambVisionReviewInfor = StarDreambVisionReviewInfor
		},
		deleteReview(state, VhId) {
			state.StarDreambVisionReviewInfor = state.StarDreambVisionReviewInfor.filter((item) => item.VhId !== VhId)
		},
	},
	actions: {
		async getWeixinToken(context) {
			const res = await getWeixinToken()
			console.log('getWeixinToken', res);
			context.commit("setWeixinToken", res);
		},
		async getWeixinOpenid(context, code) { // 弃用
			console.log("getWeixinOpenid");
			const res = await getWeixinOpenid(code);
			console.log(res);
			const { openid, session_key } = res;
			context.commit("setWeixinOpenId", openid);
		},
		async register(context, { code, phoneCode }) {
			console.log("State", `register called, code -> ${code}, phoneCode -> ${phoneCode}`);
			const res = await getWeixinOpenid(code);
			const phoneRes = await getUserPhone(phoneCode, context.state.access_token)
			console.log(res);
			console.log(phoneRes);
			const { openid, session_key } = res;
			const { phone_info, errcode } = phoneRes;
			context.commit("setWeixinOpenId", openid);
			const { 
				province,
				city,
				district,
				formatted_address,
			 } = context.state
			const { ContentDes, MarkType } = 
				await MemgerRegisterWrite(
					openid,
					"微信用户" + randomString(6),
					"未知",
					phone_info.phoneNumber,
					province,
					city,
					district,
					formatted_address,
				);
			console.log("State", `MemgerRegisterWrite ${MarkType} ${ContentDes}`);
			if (MarkType === "true") {
				uni.showModal({
					title: "提示",
					content: "注册成功",
				})
				context.dispatch("getUserInfo")
			} else {
				uni.showModal({
					title: "提示",
					content: ContentDes,
				})
			}
		},
		async updateUserInfo(context, patch) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const userInfo = context.state.userInfo
			const newUserInfo = { ...userInfo, ...patch, MiniOpenId }
			const { ContentDes, MarkType } = await MemgerRegisterWriteForm(newUserInfo)
			console.log("State", `MemgerRegisterWrite ${MarkType} ${ContentDes}`);
			if (MarkType === "true") {
				uni.showModal({
					title: "提示",
					content: "更新成功",
				})
				context.dispatch('getUserInfo')
			} else {
				uni.showModal({
					title: "提示",
					content: ContentDes,
				})
			}
		},
		async login(context, code) {
			console.log("State", `login called, code -> ${code}`);
			const res = await getWeixinOpenid(code);
			console.log(res);
			const { openid, session_key } = res;
			context.commit("setWeixinOpenId", openid);

			const { ContentDes, MarkType } = await MemgerWhetherRegister(openid);
			console.log("State", `MemgerWhetherRegister ${MarkType} ${ContentDes}`);
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log("State", `MemgerWhetherRegister ContentDes`, ctn);
				if (!ctn || ctn.length === 0) {
					console.error("State", "User not registered.");
					// 微信用户未注册，清除登录状态
					context.commit("setLogin", { isLogin: false });
				} else {
					context.commit("setLogin", { isLogin: true, userInfo: ctn });
					context.dispatch('readMyCollect')
				}
			} else {
				console.error(ContentDes);
				// 调用检查注册接口失败，清除登录状态
				context.commit("setLogin", { isLogin: false });
			}
		},
		async getUserInfo(context) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const { ContentDes, MarkType } = await MemgerWhetherRegister(MiniOpenId);
			console.log("State", `getUserInfo ${MarkType} ${ContentDes}`);
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log("State", `MemgerWhetherRegister ContentDes`, ctn);
				if (!ctn || ctn.length === 0) {
					console.error("State", "User not registered.");
				} else {
					context.commit("setLogin", { isLogin: true, userInfo: ctn });
				}
			} else {
				console.error(ContentDes);
			}
		},
		async getImages(context) {
			console.log("getImages");
			const res = await ReadBackgroundImageInfor();
			console.log(res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit("setImages", ctn);
			} else {
				console.error(ContentDes);
			}
		},
		async getBannerImages(context) {
			console.log("getBannerImages");
			const res = await ReadBannerImageInfor();
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log("getBannerImages", ctn);
				context.commit("setBanners", ctn);
			} else {
				console.error(ContentDes);
			}
		},
		async getFont(context) {
			console.log("getFont");
			const res = await ReadFontInfor();
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log("getFont",ctn);
				const { FontFile } = ctn;
				context.commit("setFontFile", FontFile);
			} else {
				console.error(ContentDes);
			}
		},
		async getChangeLensesRule(context) {
			console.log("getChangeLensesRule");
			const res = await ReadChangeLensesRule();
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				const { ActivityContent } = ctn;
				context.commit("setActivityContent", ActivityContent);
			} else {
				console.error(ContentDes);
			}
		},
		async getNearbyShop(context, { ProviceName, CityName, CountyName }) {
			console.log("getNearbyShop", ProviceName, CityName, CountyName);
			const res = await ReadNearbyShopInfor(ProviceName, CityName, CountyName);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				const { latitude, longitude } = context.state;
				const ctnWithDistance = ctn.map((item) => {
					const distance = getDistance(latitude, longitude, Number(item.Latitude), Number(item.Longitude));
					return {...item, distance};
				});
				// console.log('context', context.state);
				console.log(ctn);
				context.commit("setNearbyShop", ctnWithDistance);
			} else {
				console.error(ContentDes);
			}
		},
		async getAllShop(context) {
			console.log("getAllShop");
			const res = await ReadNearbyShopInfor("", "", "");
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				const { latitude, longitude } = context.state;
				const ctnWithDistance = ctn.map((item) => {
					const distance = getDistance(latitude, longitude, Number(item.Latitude), Number(item.Longitude));
					return {...item, distance};
				});
				// console.log('context', context.state);
				// console.log(ctn);
				context.commit("setAllStores", ctnWithDistance);
			} else {
				console.error(ContentDes);
			}
		},
		async getReadIntroduceMainTitle(context) {
			const res = await ReadIntroduceMainTitle();
			console.log("getReadIntroduceMainTitle", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const MainTitle = JSON.parse(ContentDes);
				// console.log('context', context.state);
				console.log(MainTitle);
				context.commit("setReadIntroduceMainTitle", MainTitle);
				if (MainTitle.length > 0) {
					context.dispatch("getReadIntroduceDeputyTitle", MainTitle[0].TitleNo)
				}
			} else {
				console.error(ContentDes);
			}
		},
		async getReadIntroduceDeputyTitle(context, MainKey) {
			const res = await ReadIntroduceDeputyTitle(MainKey);
			console.log("getReadIntroduceDeputyTitle", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const DeputyTitle = JSON.parse(ContentDes);
				// console.log('context', context.state);
				console.log(DeputyTitle);
				for (var deputyTitleItem of DeputyTitle) {
					const res = await ReadIntroduceSubTitle(deputyTitleItem.TitleNo);
					const { ContentDes, MarkType } = res;
					if (MarkType === "true") {
						const SubTitle = JSON.parse(ContentDes);
						deputyTitleItem.children = SubTitle;
					}
				}
				context.commit("setReadIntroduceSubDir", DeputyTitle);
			} else {
				console.error(ContentDes);
			}
		},
		async getReadIntroduceContent(context, SubKey) {
			const res = await ReadIntroduceContent(SubKey);
			console.log("getReadIntroduceContent", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const Content = JSON.parse(ContentDes);
				const {tmp} = Content;
				if (tmp && tmp.length > 0) {
					context.commit("setIntroduceContent", tmp[0]);
				} else {
					context.commit("setIntroduceContent", {});
				}
			} else {
				console.error(ContentDes);
			}
		},
		async addEstablishWearerInfor(context, form) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const res = await EstablishWearerInfor({...form, MiniOpenId});
			console.log("addEstablishWearerInfor", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				uni.showModal({
					content: "添加成功",
					title:"提示",
				})
				context.dispatch('getReadWearerInfor')
			} else {
				console.error(ContentDes);
				uni.showModal({
					content:ContentDes,
					title:"提示",
				})
			}
		},
		async getReadWearerInfor(context) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const res = await ReadWearerInfor(MiniOpenId);
			console.log("getReadWearerInfor", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit("setWearers", ctn.tmp || []);
			} else {
				console.error(ContentDes);
			}
		},
		async postEditVisionArchivesInfor(context, form) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			await uni.showLoading({
				title: '提交中'
			})
			const res = await EditVisionArchivesInfor({...form, MiniOpenId});
			console.log("getReadWearerInfor", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				context.dispatch('ReadVisionArchivesInfor')
				context.dispatch('ReadStarDreambCurInfor')
				uni.showModal({
					content: "添加成功",
					title:"提示",
				})
			} else {
				console.error(ContentDes);
			}
			uni.hideLoading()
		},
		async ReadVisionArchivesInfor(context) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const WearerCode = context.state.wearers[context.state.selectedWearerIndex]?.WearerCode;
			if (!WearerCode) {
				return;
			}
			const res = await ReadVisionArchivesInfor(MiniOpenId, WearerCode)
			console.log("ReadVisionArchivesInfor", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit("setVisionArchives", ctn.tmp || []);
			} else {
				console.error(ContentDes);
			}
		},
		async ReMoveVisionArchivesInfor(context, VhNo) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const WearerCode = context.state.wearers[context.state.selectedWearerIndex].WearerCode;
			const res = await ReMoveVisionArchivesInfor(MiniOpenId, WearerCode, VhNo);
			console.log("ReMoveVisionArchivesInfor", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				// const ctn = JSON.parse(ContentDes);
				// console.log(ctn);
				uni.showToast({
					title: '删除成功',
					mask: false,
					icon: 'none',
				})
				context.dispatch('ReadVisionArchivesInfor');
				context.commit('deleteReview', VhNo);
			} else {
				console.error(ContentDes);
				uni.showModal({
					content: ContentDes,
					title:"提示",
				})
			}
		},
		async addMyCollect(context, form) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const res = await EditMyCollect(MiniOpenId, "添加",form.CollectType, form.TypeCode)
			console.log("addMyCollect", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				uni.showToast({
					title: ContentDes,
					mask: false,
					icon: 'none',
				})
				context.dispatch('readMyCollect')
			} else {
				console.error(ContentDes);
			}
		},
		async delMyCollect(context, form) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const res = await EditMyCollect(MiniOpenId, "移除",form.CollectType, form.TypeCode)
			console.log("delMyCollect", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				uni.showToast({
					title: ContentDes,
					mask: false,
					icon: 'none',
				})
				context.dispatch('readMyCollect')
			} else {
				console.error(ContentDes);
			}
		},
		async readMyCollect(context) {
			let myShopCollect = []
			let myDocCollect = []
			let SmallOpenId = context.state.openid
			if (!SmallOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			
			{
				let res = await ReadMyCollect(SmallOpenId, "门店")
				console.log("readMyCollect 门店", res);
				let { ContentDes, MarkType } = res;
				if (MarkType === "true") {
					const ctn = JSON.parse(ContentDes);
					console.log(ctn);
					myShopCollect = ctn;
				} else {
					console.error(ContentDes);
				}
			}

			{
				let res = await ReadMyCollect(SmallOpenId, "文章")
				console.log("readMyCollect 文章", res);
				let { ContentDes, MarkType } = res;
				if (MarkType === "true") {
					const ctn = JSON.parse(ContentDes);
					console.log(ctn);
					myDocCollect = ctn;
				} else {
					console.error(ContentDes);
				}
			}

			context.commit('setCollect', { myDocCollect: myDocCollect.tmp || [], myShopCollect: myShopCollect.tmp || [] });
		},
		async SecurityCodeCheck(context, code) {
			uni.showLoading({
				title: '查询中'
			})
			let res = await SecurityCodeCheck(code)
			console.log("SecurityCodeCheck", res);
			let { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit('setCheckResult', ctn)
			} else {
				console.error(ContentDes);
				uni.showToast({
					title: ContentDes,
					mask: false,
					icon: 'none',
				})
				context.commit('setCheckResult', null)
			}
			uni.hideLoading();
		},
		async StarDreambActivate(context, form) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const res = await StarDreambActivate({...form, MiniOpenId});
			console.log("StarDreambActivate", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				// context.dispatch('ReadStarDreambInfor')
				context.dispatch('ReadStarDreambCurInfor')
				uni.showModal({
					content: "激活星梦保成功",
					title:"提示",
				})
			} else {
				console.error(ContentDes);
				uni.showModal({
					content: "激活星梦保失败，" + ContentDes,
					title:"提示",
				})
			}
		},
		async ReadStarDreambInfor(context) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const WearerCode = context.state.wearers[context.state.selectedWearerIndex].WearerCode;
			const res = await ReadStarDreambInfor(MiniOpenId, WearerCode)
			console.log("ReadStarDreambInfor", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit("setStarHistory", ctn.tmp || []);
			} else {
				console.error(ContentDes);
			}
		},
		async ReadChildInforProtectRule(context) {
			const res = await ReadChildInforProtectRule();
			console.log('ReadChildInforProtectRule', res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit("setRuleContent", ctn.RuleContent || '');
			} else {
				console.error(ContentDes);
			}
		},
		async ReadTermAgreement(context) {
			const res = await ReadTermAgreement();
			console.log('ReadTermAgreement', res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit("setTermAgreement", ctn.AgreeContent || '');
			} else {
				console.error(ContentDes);
			}
		},
		async StarDreambVisionReview(context, form) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const WearerCode = context.state.wearers[context.state.selectedWearerIndex]?.WearerCode;
			if (!WearerCode) {
				uni.showModal({
					title: "提示",
					content: "请先添加佩戴者",
				})
				return;
			}
			const res = await StarDreambVisionReview({...form, MiniOpenId, WearerCode})
			console.log("StarDreambVisionReview", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				uni.showModal({
					content: "提交成功",
					title:"提示",
				})
				context.dispatch('ReadStarDreambVisionReviewInfor', form.ActivateVisionId)
			} else {
				console.error(ContentDes);
				uni.showModal({
					content: ContentDes,
					title:"提示",
				})
			}
		},
		async ReadStarDreambCurInfor(context) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const WearerCode = context.state.wearers[context.state.selectedWearerIndex]?.WearerCode;
			if (!WearerCode) {
				uni.showModal({
					title: "提示",
					content: "请先添加佩戴者",
				})
				return;
			}
			const res = await ReadStarDreambCurInfor(MiniOpenId, WearerCode)

			console.log("ReadStarDreambCurInfor", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit("setStarDreambCurInfor", ctn.tmp || []);
			} else {
				console.error(ContentDes);
			}
		},
		async ReadStarDreambVisionReviewInfor(context, ActivateVhId) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const WearerCode = context.state.wearers[context.state.selectedWearerIndex]?.WearerCode;
			if (!WearerCode) {
				uni.showModal({
					title: "提示",
					content: "请先添加佩戴者",
				})
				return;
			}
			const res = await ReadStarDreambVisionReviewInfor(MiniOpenId, WearerCode, ActivateVhId)

			console.log("ReadStarDreambVisionReviewInfor", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				context.commit("setStarDreambVisionReviewInfor", ctn.tmp || []);
			} else {
				console.error(ContentDes);
			}
		},
		async ReadMemberReceive(context) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const res = await ReadMemberReceive(MiniOpenId)

			console.log("ReadMemberReceive", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				const ctn = JSON.parse(ContentDes);
				console.log(ctn);
				// context.commit("setStarDreambCurInfor", ctn.tmp || []);
				return ctn.tmp || [];
			} else {
				console.error(ContentDes);
			}
			return [];
		},
		async ApplyChangeLensSubmit(context, form) {
			const MiniOpenId = context.state.openid
			if (!MiniOpenId) {
				uni.showModal({
					title: "提示",
					content: "请先登录",
				})
				return;
			}
			const WearerCode = context.state.wearers[context.state.selectedWearerIndex]?.WearerCode;
			if (!WearerCode) {
				uni.showModal({
					title: "提示",
					content: "请先添加佩戴者",
				})
				return;
			}
			const res = await ApplyChangeLensSubmit({...form, MiniOpenId, WearerCode})

			console.log("ApplyChangeLensSubmit", res);
			const { ContentDes, MarkType } = res;
			if (MarkType === "true") {
				uni.showModal({
					content: "提交成功",
					title:"提示",
				})
				context.dispatch('ReadStarDreambVisionReviewInfor', form.ActivateVisionId)
			} else {
				console.error(ContentDes);
				uni.showModal({
					content: ContentDes,
					title:"提示",
				})
			}
		}
	}
})

export default store